<template>
<div>
  <Row  type="flex" justify="end">
    <i-col >
    <Button @click="back" type="text" icon="md-arrow-back">返回</Button>
    </i-col>
    <i-col flex="auto" style="text-align: right" >
      <Button @click="showPackageBoxModal(1,null)" type="warning" style="margin-right: 0.5rem" icon="md-add"  >新建包裹</Button>
      <Button @click="showPackageModal(1,null)" type="info" icon="md-add">新建物流单</Button>
    </i-col>
  </Row>

  <divider></divider>
  <Row type="flex" justify="start"  >
    <KeyValueView title="订单编号">{{shortOrderInfo.serialNumber}}</KeyValueView>
    <KeyValueView v-if="shortOrderInfo.checkoutTime" title="付款时间">{{getFormatedDateTime(shortOrderInfo.checkoutTime)}}</KeyValueView>
    <KeyValueView title="国家" :value="shortOrderInfo.country"></KeyValueView>
    <KeyValueView title="金额" :value="'US$ '+shortOrderInfo.actualPayment"></KeyValueView>
    <KeyValueView v-if="orderStateEnum.filter(i => i.code == shortOrderInfo.orderState.state).length>0" title="订单状态">{{orderStateEnum.filter(i => i.code == shortOrderInfo.orderState.state)[0].cnName}}</KeyValueView>
    <KeyValueView v-if="shipStateEnum.filter(i => i.code == shortOrderInfo.orderState.shipState).length>0" title="发货状态">{{shipStateEnum.filter(i => i.code == shortOrderInfo.orderState.shipState)[0].cnName}}</KeyValueView>

  </Row>

  <divider></divider>

  <Tabs size="small" type="card"  animated="false" @on-click="resetRadioLabel($event)" >
    <TabPane name="1" key="-1" label="已出库产品" >
      <div>
        <Row style="padding: 0.5rem 0" justify="center" align="bottom">
          <i-col flex="auto" style="text-align: left">
          <Select v-model="selectedPackage" clearable style="width: auto;min-width: 13rem"  placeholder="选择物流单" @on-change="packageChange($event)" size="small">
            <Option v-for="(pck, pIndex)  in packageList" :value="pck" :key="pIndex" >
              {{ getLabel(pIndex,pck)}}
            </Option>
          </Select>
          <Select v-model="selectedBox"  multiple style="width: auto;min-width: 13rem;margin-left: 2rem;margin-right: 2rem;"  placeholder="选择包裹" @on-change="boxChange(true)" size="small">
            <Option v-for="(item,index) in packBoxArray" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
            <KeyValueView title="产品编码"  :value="shortOrderInfo.country">
              <Input v-model="productCode" @on-clear="productCodeKeyUp" @on-keyup="productCodeKeyUp" clearable placeholder="请输入" style="width: 200px" />
            </KeyValueView>
          </i-col>

          <i-col>
            <Checkbox v-model="isShow.isShowPend" @on-change="pendingProduct">仅显示未分配产品</Checkbox>
            <Checkbox v-model="isShow.isShowColor">不显示色卡</Checkbox>
            <Checkbox v-model="isShow.isWorkingModel">拆单模式</Checkbox>
          </i-col>
        </Row>

        <br>
        <Row v-if="product.productItemVoList.length>0"  v-for="(product,index) in productListFilter" >
            <Row class="order_product_row"  style="width: 100%">
              <i-col  :xs="24" :sm="3">
                <img :src="product.productImage"
                     style="width:99%;max-width:100px;max-height:100px;"
                     @click="status.modalImage.url=product.productImage;status.modalImage.isShow = true;"/>
              </i-col>
              <i-col :xs="24" :sm="21" align="left" >
                <div style="padding-left: 0.5rem">
                  <Row>
                    <i-col flex="auto">
                      <KeyValueView title="序号" >{{index+1}}</KeyValueView>
                      <KeyValueView title="产品编码" >
                        <a target="_blank" :href="$tiyProductUrl(product.productCode)">{{product.productCode}}</a>
                      </KeyValueView>
                    </i-col>
                    <Button size="small" @click.stop="showBatchAddProduct()" type="success"  v-show="isShow.isWorkingModel">加入包裹</Button>
                  </Row>

                  <Row>
                    <KeyValueView title="已出库件数" >{{product.count}}</KeyValueView>
                    <KeyValueView title="单件毛重" >{{product.weight}}g</KeyValueView>
                    <KeyValueView title="累计毛重" >{{product.count*product.weight}}g</KeyValueView>
                  </Row>
                  <Row>
                    <Checkbox v-show="isShow.isWorkingModel" style="margin-top: 0.2rem" v-model="product.checkAll" @on-change="batchCheckAll(product)">全部选中</Checkbox>
                  </Row>


                </div>
<!--                <KeyValueView title="产品名称" oneline v-mobile="false">{{product.productName}}</KeyValueView>-->
                <div v-if="!isShow.isShowColor" >
                  <divider dashed  style="margin: 12px 0"></divider>
                  <Row v-for="(colorItem, colorIndex) in product.productItemVoList" style="padding: 0.2rem 0.5rem"  class="item_hover">
                    <i-col flex="auto">
                      <Checkbox :disabled="colorItem.sumBoxCount>=colorItem.number" v-show="isShow.isWorkingModel" @on-change="batchCheck(colorItem,product)" v-model="colorItem.checked"></Checkbox>
                      <KeyValueView title="色卡图">
                        <span style="cursor: pointer;"
                              @click="status.modalImage.url=yunPath + colorItem.originalImagePath;status.modalImage.isShow = true;">点我查看</span>
                      </KeyValueView>
                      <KeyValueView title="色卡">
                        {{colorItem.color}}
                      </KeyValueView>
                      <KeyValueView title="尺码">{{colorItem.sizeName}}</KeyValueView>
                      <KeyValueView title="数量">{{colorItem.number}}</KeyValueView>
                    </i-col>
                    <Tag type="dot" size="small" @dblclick.native="ShowModifyBoxCount(colorItem,box)" style="cursor: pointer" title="双击可编辑"
                         v-for="(box,bIndex) in colorItem.boxArray" :color="getBoxColor(box.boxId)" >{{ box.boxName}}: {{box.boxCount}}</Tag>
                  </Row>
                </div>
              </i-col>
            </Row>
          </Row>
        <Row class="order_product_row_top"></Row>
      </div>
    </TabPane>
    <TabPane name="2" key="-2" label="物流单和包裹维护" >
        <div style="text-align: left; border:solid 1px #e0e0e0;" >
          <div style="background: #f3f3f9;padding: 0.5rem 1rem">
            <strong>待分配包裹</strong>
          </div>
          <List size="small" style="margin:0.5rem">
              <ListItem v-if="isEmpty(item.packageId)" v-for="(item,index) in packageBoxList" class="item_hover">
                <i-col flex="auto">
                  <Tag :color="item.type===1?'green':'default'" style="margin-right: 1rem;"> {{item.type===1?'箱子':'袋子'}}</Tag>
                  <KeyValueView title="名称" :value="item.name" style="margin-right: 1rem;"/>
                  <KeyValueView title="尺寸" :value="item.size"/>
                  <KeyValueView title="重量" :value="item.weight+'g'" v-show="item.weight!==null"/>
                </i-col>
                <Dropdown style="margin-left: 3rem" trigger="click" @on-click="dropdownClick($event,item)">
                  <a href="javascript:void(0)" style="color: #757575">
                    更多操作
                    <Icon type="ios-arrow-down"></Icon>
                  </a>
                  <template #list>
                    <DropdownMenu >
                      <DropdownItem name="1">编辑</DropdownItem>
                      <DropdownItem name="2">删除</DropdownItem>
                    </DropdownMenu>
                  </template>
                </Dropdown>
              </ListItem>
            </List>
        </div>
        <div style="text-align: left;margin-top: 2rem; border:solid 1px #e0e0e0;" v-for="(pack,index) in packageList">
          <div style="background: #f3f3f9;padding: 0.5rem 1rem">
            <strong style="margin-right: 3rem">物流单号: {{pack.waybill}}</strong>
              <KeyValueView title="快递公司">{{pack.deliveryCompanyName}}</KeyValueView>
              <KeyValueView title="包裹状态">{{getDictName('packageStateDict',pack.state)}}</KeyValueView>
              <Button size="small" type="default"  @click.native="showPackageModal(2,pack)" >编辑</Button>
          </div>
          <List size="small"  style="margin: 0.5rem;">
              <ListItem v-for="(item,index) in pack.packageBoxList"  class="item_hover">
                <i-col flex="auto">
                <Tag :color="item.type===1?'green':'default'" style="margin-right: 1rem;"> {{item.type===1?'箱子':'袋子'}}</Tag>
                <KeyValueView title="名称" :value="item.name" style="margin-right: 1rem;"/>
                <KeyValueView title="尺寸" :value="item.size"/>
                <KeyValueView title="重量" :value="item.weight+'g'" v-show="item.weight!==null"/>
                <KeyValueView v-if="isEmpty(item.packageId)" title="物流单号" :value="packageList.filter(i => i.id == item.packageId)[0].waybill"/>
                </i-col>

                <Dropdown style="margin-left: 3rem" trigger="click" @on-click="dropdownClick($event,item)">
                  <a href="javascript:void(0)" style="color: #757575">
                    更多操作
                    <Icon type="ios-arrow-down"></Icon>
                  </a>
                  <template #list>
                    <DropdownMenu>
                      <DropdownItem name="1">编辑</DropdownItem>
                      <DropdownItem name="2">删除</DropdownItem>
                    </DropdownMenu>
                  </template>
                </Dropdown>

              </ListItem>
          </List>


        </div>




    </TabPane>
    <TabPane name="3" key="-3" label="未质检产品">
      <div>

        <br>
        <Row v-if="product.productItemVoList.length>0"  v-for="(product,index) in notQualityCheckProducts" >
          <Row class="order_product_row"  style="width: 100%">
            <i-col  :xs="24" :sm="3">
              <img :src="product.productImage"
                   style="width:99%;max-width:100px;max-height:100px;"
                   @click="status.modalImage.url=product.productImage;status.modalImage.isShow = true;"/>
            </i-col>
            <i-col :xs="24" :sm="21" align="left" >
              <div style="padding-left: 0.5rem">
                <Row>
                  <i-col flex="auto">
                    <KeyValueView title="序号" >{{index+1}}</KeyValueView>
                    <KeyValueView title="产品编码" >
                      <a target="_blank" :href="$tiyProductUrl(product.productCode)">{{product.productCode}}</a>
                    </KeyValueView>
                  </i-col>
                </Row>

                <Row>
                  <KeyValueView title="数量" >{{product.count}}</KeyValueView>
                  <KeyValueView title="单件毛重" >{{product.weight}}g</KeyValueView>
                  <KeyValueView title="累计毛重" >{{product.count*product.weight}}g</KeyValueView>
                </Row>



              </div>
              <!--                <KeyValueView title="产品名称" oneline v-mobile="false">{{product.productName}}</KeyValueView>-->
              <div  >
                <divider dashed  style="margin: 12px 0"></divider>
                <Row v-for="(colorItem, colorIndex) in product.productItemVoList" style="padding: 0.2rem 0.5rem"  class="item_hover">
                  <i-col flex="auto">
                    <KeyValueView title="色卡图">
                        <span style="cursor: pointer;"
                              @click="status.modalImage.url=yunPath + colorItem.originalImagePath;status.modalImage.isShow = true;">点我查看</span>
                    </KeyValueView>
                    <KeyValueView title="色卡">
                      {{colorItem.color}}
                    </KeyValueView>
                    <KeyValueView title="尺码">{{colorItem.sizeName}}</KeyValueView>
                    <KeyValueView title="数量">{{colorItem.number+colorItem.lastAmount}}</KeyValueView>
                  </i-col>

                  <Tag v-if="colorItem.lastAmount>0" color="green" >未揽件</Tag>
                  <Tag v-if="colorItem.state==1" color="warning" >{{getSolutionType(colorItem.solutionType)}}</Tag>
                  <Tag v-if="colorItem.solutionType==4" color="magenta" >{{getSolutionType(colorItem.solutionType)}}</Tag>
                  <Tag v-if="colorItem.faultState==1" color="success" >待质检</Tag>
                  <Tag v-if="colorItem.faultState==2&&colorItem.solutionType==3" color="success" >待质检</Tag>
                  <Tag v-if="colorItem.faultState==2&&colorItem.state==0" color="error" >问题件</Tag>
                </Row>
              </div>
            </i-col>
          </Row>
        </Row>
        <Row class="order_product_row_top"></Row>
      </div>
    </TabPane>
    <TabPane context-menu v-for="(pck, pIndex) in packageList" :name="pck" :key="pIndex" :label="getLabel(pIndex,pck)"   v-if="false">
      <Row type="flex" justify="start" align="middle">
        <RadioGroup v-model="radioLabel"  style="text-align: left" @on-change="">
          <Radio v-for="(pckBox, index) in pck.packageBoxList" :key="index" :label="index*1+1">
              <span style="margin-left:0.5rem " >
               {{pckBox.name}}
              </span>
          </Radio>
        </RadioGroup>
      </Row>
    </TabPane>
    <template slot="contextMenu">
      <DropdownItem @click.native="showPackageModal(2,null)" style="color: #1bed14">编辑</DropdownItem>
    </template>
  </Tabs>

  <!--修改包裹的产品数量-->
  <Modal
    v-model="status.modalBoxCountModify.isShow" title="修改产品数量" :styles="{align:'center',width: '50%'}"
    :closable="true" :mask-closable="false" :loading="status.modalBoxCountModify.isLoading"
    @on-ok="modifyBoxCount('modifyBox')">
    <Form ref="modifyBox" :model="tData.modifyBoxCount"  :label-width="100"
          class="modal_new_form">
      <KeyValueView title="包裹名称">{{tData.modifyBoxCount.boxName}}</KeyValueView>
      <KeyValueView title="色卡">{{tData.modifyBoxCount.color}}</KeyValueView>
      <KeyValueView title="尺码">{{tData.modifyBoxCount.sizeName}}</KeyValueView>
      <KeyValueView title="数量">
        <InputNumber :max="tData.modifyBoxCount.maxCount" :min="0" :step="1" v-model="tData.modifyBoxCount.boxCount" size="small" controls-outside></InputNumber>
      </KeyValueView>

    </Form>
  </Modal>


  <!--新增物流单-->
  <Modal
    v-model="status.modalPackage.isShow" :title="status.modalPackage.title" :styles="{align:'center',width: '50%'}"
    :closable="true" :mask-closable="false" :loading="status.modalPackage.isLoading"
    @on-ok="addPackage('paramPackage')">
    <Form ref="paramPackage" :model="package" :rules="status.packageRules" :label-width="100"
          class="modal_new_form">
      <FormItem label="快递公司" prop="deliveryCompany">
        <Select v-model="package.deliveryCompany" placeholder="请选择" :label-in-value=true clearable
                class="modal_form_input">
          <Option v-for="item in deliverCompanyList" :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </FormItem>
      <FormItem label="运送单号" prop="waybill">
        <Input v-model.trim="package.waybill" placeholder="请输入"
               class="modal_form_input"></Input>
      </FormItem>
      <FormItem v-if="status.modalPackage.type==1" label="未分配包裹" prop="box">
        <Checkbox v-model="isCheckedAllBox" @on-change="handleCheckAll">全选</Checkbox>
        <CheckboxGroup v-model="boxSelected" @on-change="checkChange" >
          <Checkbox v-if="isEmpty(item.packageId)" v-for="item in packageBoxList" :key="item.id" :label="item" >{{item.name}}</Checkbox>
        </CheckboxGroup>
      </FormItem>

      <FormItem v-if="status.modalPackage.type==2" label="包裹" prop="box">
        <Transfer
          :data="sourceData"
          :target-keys="targetData"
          :render-format="boxLabel"
          :titles="titles"
          @on-change="handleChange1"></Transfer>
      </FormItem>
    </Form>
  </Modal>

  <!--新增实体箱包-->
  <Modal
    v-model="status.modalPackageBox.isShow" :title="status.modalPackageBox.title"
    :closable="true" :mask-closable="false" :loading="status.modalPackageBox.isLoading"
    @on-ok="addPackageBox('paramPackageBox')">
    <Form ref="paramPackageBox" :model="packageBox" :rules="status.packageBoxRules" :label-width="100"
          class="modal_new_form">
      <FormItem v-if="status.modalPackageBox.type==2" label="物流单" prop="packageId" clearable>
        <Select v-model="packageBox.packageId" placeholder="请选择" :label-in-value=true
                class="modal_form_input">
          <Option v-for="(item,index) in packageList" :value="item.id" :key="item.id">包裹{{index*1+1}}(运单号):{{item.waybill}}</Option>
        </Select>
      </FormItem>
      <FormItem label="箱包名称" prop="name">
        <Input v-model.trim="packageBox.name" placeholder="请输入"
               class="modal_form_input"></Input>
      </FormItem>
      <FormItem label="类型" >
        <RadioGroup v-model="packageBox.type" >
          <Radio label="1">箱</Radio>
          <Radio label="2">袋</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem v-if="status.modalPackageBox.type==2" label="包装尺寸" prop="size">
        <Input v-model.trim="packageBox.size" placeholder="请输入"
               class="modal_form_input"></Input>
      </FormItem>
      <FormItem v-if="status.modalPackageBox.type==2" label="包装重量(g)" prop="weight">
        <InputNumber v-model.trim="packageBox.weight" placeholder="请输入" :min=0 :step=1 :precision=0 class="modal_form_input"></InputNumber>
      </FormItem>
    </Form>
  </Modal>

  <!--产品加入包裹-->
  <Modal
    v-model="status.modalProductAdd.isShow" title="加入包裹" width="80%"
    :closable="true" :mask-closable="false" :loading="status.modalProductAdd.isLoading"
    @on-ok="addProduct('addProduct')">
    <Form ref="addProduct" :model="params.addProduct" :rules="status.productRules" :label-width="100"
          class="modal_new_form">
      <FormItem  label="加入包裹" prop="boxId">
        <Select v-model="params.addProduct.boxId" placeholder="请选择" :label-in-value=true
                class="modal_form_input">
          <Option v-for="(item,index) in packageBoxList" :value="item.id" :key="item.id">{{item.name}} ({{item.type==1?"箱":"袋"}})</Option>
        </Select>
      </FormItem>
      <FormItem label="产品信息" >
        <Row   style="width: 100%">
          <i-col  :xs="24" :sm="3">
            <img :src="productInfo.productImage"
                 style="width:99%;max-width:100px;max-height:100px;"
                 @click="status.modalImage.url=productInfo.productImage;status.modalImage.isShow = true;"/>
          </i-col>
          <i-col :xs="24" :sm="21" align="left">
            <div>
              <KeyValueView title="产品编码" >
                <a target="_blank" :href="$tiyProductUrl(productInfo.productCode)">{{productInfo.productCode}}</a>
              </KeyValueView>
              <KeyValueView title="件数" >{{productInfo.count}}</KeyValueView>
            </div>

            <divider dashed  style="margin: 12px 0"></divider>
            <Checkbox v-model="isCheckedAllColor" @on-change="colorCheckAll" >全选</Checkbox>
            <CheckboxGroup v-model="params.addProduct.colorItemIds" @on-change="checkChangeColor">
              <div v-if="isEmpty(colorItem.packageBoxId)" v-for="(colorItem, colorIndex) in productInfo.productItemVoList" style="padding: 0.3rem 0" >
                <Checkbox :label="colorItem.id">{{check}}</Checkbox>
                <KeyValueView title="色卡图">
                        <span style="cursor: pointer;"
                              @click="status.modalImage.url=yunPath + colorItem.originalImagePath;status.modalImage.isShow = true;">点我查看</span>
                </KeyValueView>
                <KeyValueView title="色卡">
                  {{colorItem.color}}
                </KeyValueView>
                <KeyValueView title="尺码">{{colorItem.sizeName}}</KeyValueView>
                <KeyValueView title="数量">
                  <InputNumber :max="colorItem.number" :min="1" :step="1" :value="colorItem.number" size="small" controls-outside></InputNumber>
                </KeyValueView>

              </div>
            </CheckboxGroup>

          </i-col>
        </Row>
      </FormItem>

    </Form>
  </Modal>

  <!--包裹批量添加产品-->
  <Modal
    v-model="status.modalBatchProductAdd.isShow" title="添加产品" width="60"
    :closable="true" :mask-closable="false" :loading="status.modalBatchProductAdd.isLoading"
    @on-ok="batchAddProduct('addProducts')">
    <Form ref="addProducts" :model="params.addProduct" :rules="status.productRules" :label-width="100"
          class="modal_new_form">
      <FormItem  label="包裹" prop="boxId">
        <Select v-model="params.addProduct.boxId" placeholder="请选择" :label-in-value=true
                class="modal_form_input">
          <Option v-for="(item,index) in packageBoxList" :value="item.id" :key="item.id">{{item.name}} ({{item.type==1?"箱":"袋"}})</Option>
        </Select>
      </FormItem>
      <FormItem label="产品信息" >
        <Row v-if="product.productItemVoList.length>0" v-for="(product,index) in productListFiltered" >
          <Row class="order_product_row"  style="width: 100%">
          <i-col  :xs="24" :sm="3">
            <img :src="product.productImage"
                 style="width:99%;max-width:100px;max-height:100px;"
                 @click="status.modalImage.url=product.productImage;status.modalImage.isShow = true;"/>
          </i-col>
          <i-col :xs="24" :sm="21" align="left">
            <div>
              <KeyValueView title="产品编码" >
                <a target="_blank" :href="$tiyProductUrl(product.productCode)">{{product.productCode}}</a>
              </KeyValueView>
              <KeyValueView title="货源">
                <span  @click="showProductSupply(product.productId)" style="color: #1e93ff;cursor: pointer"  >查看货源</span>
              </KeyValueView>

              <br>
              <KeyValueView title="一档售价" >${{product.originalPrice}}</KeyValueView>
              <KeyValueView title="实际支付" >${{product.actualPrice}}</KeyValueView>
              <KeyValueView title="正常件数" >{{product.count}}</KeyValueView>

            </div>
            <KeyValueView title="产品名称" oneline v-mobile="false">{{product.productName}}</KeyValueView>
          </i-col>
          <i-col :xs="24" :sm="24" align="left">
            <divider dashed  style="margin: 12px 0"></divider>
            <Checkbox v-model="product.checkAll" @on-change="batchCheckAll(product)">全选</Checkbox>
              <div v-for="(colorItem, colorIndex) in product.productItemVoList" style="padding: 0.3rem 0" >
                <Checkbox @on-change="batchCheck(colorItem,product)" v-model="colorItem.checked"></Checkbox>
                <KeyValueView title="色卡图">
                        <span style="cursor: pointer;"
                              @click="status.modalImage.url=yunPath + colorItem.originalImagePath;status.modalImage.isShow = true;">点我查看</span>
                </KeyValueView>
                <KeyValueView title="色卡">
                  {{colorItem.color}}
                </KeyValueView>
                <KeyValueView title="尺码">{{colorItem.sizeName}}</KeyValueView>
                <KeyValueView title="数量">
                  <InputNumber :max="colorItem.number-colorItem.sumBoxCount" :min="1"  :step="1" v-model="colorItem.boxCount"  size="small" controls-outside></InputNumber>
                </KeyValueView>
              </div>
          </i-col>
        </Row>
        </Row>
        <Row class="order_product_row_top"></Row>
      </FormItem>

    </Form>
  </Modal>

  <!--查看产品货源弹出框-->
  <Modal v-model="status.modalSupply.isShow" title="产品货源"
         :styles="{align:'center',width:'70%',padding:'2rem'}" :scrollable=true>
    <!--表格和分页-->
    <Table stripe border :columns="productSupplyTable" :data="tData.productSupplyList"
           class="table_css" no-data-text="暂无数据"></Table>
  </Modal>

  <!--查看图片弹出框-->
  <Modal v-model="status.modalImage.isShow" title="" :styles="{align:'center'}" :scrollable=true>
    <div slot="footer"></div>
    <div align="center"><Img :src="status.modalImage.url" style="max-width: 300px"/></div>
  </Modal>

</div>
</template>

<script>
import KeyValueView from "../widgets/KeyValueView";
import tiyData from "./js/orderShipPackage/order_package_data";
import detailData from "./js/orderDetails/order_detail_data.js";
import {showProductSupply, webItemRecord,refundItems,deliver} from "./js/orderDetails/order_detail_fun";
import {isEmpty} from "../js/commonUtils";
import {
  getPackageInfo,
  addPackage,
  addPackageBox,
  addProduct,
  deletepackageBox,
  queryNotQualityProducts,
  updatePackageBoxProduct,
} from "./js/orderShipPackage/order_package_fun";

export default {
  components: {KeyValueView},
  data() {
    return {
      status: tiyData.tStatus,
      params: tiyData.tParams,
      tData: tiyData.tData,
      packageList: tiyData.tData.packageList,
      productList: tiyData.tData.productList,
      productListFilter: tiyData.tData.productListFilter,
      productListFiltered: [],
      packageBoxList: tiyData.tData.packageBoxList,
      package: tiyData.tParams.package,
      packageBox: tiyData.tParams.packageBox,
      productInfo:tiyData.tParams.product,
      notQualityCheckProducts:[],
      value:'-1',
      radioLabel:1,
      radioLabel2:"全部",
      productSupplyTable: detailData.productSupplyTable(this),
      shortOrderInfo: this.$route.params.shortOrderInfo,
      orderStateEnum: this.$store.getters.order.orderStateEnum,
      shipStateEnum: this.$store.getters.order.shipStateEnum,
      yunPath: this.$store.getters.imgPrefix,
      orderStateDict: this.$store.getters.dictionaries.orderStateDict,
      //字典 包裹状态
      packageStateDict: this.$store.getters.dictionaries.packageStateDict,
      //字典 订单子项状态
      orderItemStateDict: this.$store.getters.dictionaries.orderItemStateDict,
      //字典 快运公司
      deliverCompanyList: this.$store.getters.dictionaries.deliverCompanyList,
      isCheckedAllBox: false,
      isCheckedAllColor: false,
      isShow:{
        isShowPend:false,
        isWorkingModel:false,
        isShowColor:false,//不显示色卡
      },
      check: '',
      selectedBoxId:'',
      boxSelected: [],
      titles:["待分配包裹","已分配包裹"],
      sourceData:[],
      targetData:[],
      packBoxArray:[],
      selectedPackage:{},
      selectedBox:[],
      productCode:'',
      tRole: {//权限
        ORDER_1_209: "ORDER-1-209",//取消订单（款项未到账）---
        ORDER_1_210: "ORDER-1-210",//整单退款---
        ORDER_1_211: "ORDER-1-211",//整单发货---
        ORDER_1_212: "ORDER-1-212",//拆单发货---
        ORDER_1_213: "ORDER-1-213",//提交缺货退款---
        ORDER_1_215: "ORDER-1-215",//跟踪包裹----
        ORDER_1_216: "ORDER-1-216",//修改运单号----
        ORDER_1_225: "ORDER-1-225",//查看货源

      },
    }
  },
  methods:{
    switchBox(id){
      this.selectedBoxId = id;
    },
    productCodeKeyUp(){
      this.boxChange(false);
    },
    modifyBoxCount(name){
      updatePackageBoxProduct(this,tiyData,name);
    },
    ShowModifyBoxCount(colorItem,boxProduct){
      this.tData.modifyBoxCount.id=boxProduct.id;
      this.tData.modifyBoxCount.color=colorItem.color;
      this.tData.modifyBoxCount.sizeName=colorItem.sizeName;
      this.tData.modifyBoxCount.boxName=boxProduct.boxName;
      this.tData.modifyBoxCount.boxCount=boxProduct.boxCount;
      this.tData.modifyBoxCount.maxCount=colorItem.number-colorItem.sumBoxCount+boxProduct.boxCount;
      tiyData.tStatus.modalBoxCountModify.isShow = true;
    },
    getSolutionType(solutionType){
      let text="";
      switch (solutionType){
        case 1:
          text="问题件:联系商家补货/换货";
          break;
        case 2:
          text="问题件:暂未决定";
          break;
        case 3:
          text="恢复正常";
          break;
        case 4:
          text="问题件:退款";
          break;
      }
      return text;
    },
    deleteBox(box){
      deletepackageBox(this,tiyData,box);
    },
    packageChange(pack){
      let self=this;
      self.isShow.isShowPend=false;
      self.selectedBox.splice(0,self.selectedBox.length);
      if(pack==null){
        self.packBoxArray=[...this.packageBoxList];
        self.productListFilter=JSON.parse(JSON.stringify(self.productList));
      }else{
        self.packBoxArray=this.packageBoxList.filter(i=>i.packageId==pack.id);
        self.productListFilter=JSON.parse(JSON.stringify(self.productList));
        self.productListFilter.forEach(product=>{
          for(let i=0;i<product.productItemVoList.length;i++){
            let bool=false;
            self.packBoxArray.forEach(box=>{
              if(!isEmpty(product.productItemVoList[i].boxArray)&&product.productItemVoList[i].boxArray.filter(arr=>arr.boxId==box.id).length>0){
                bool=true;
              }
            })
            if(!bool){
              product.productItemVoList.splice(i,1);
              i--;
            }
          }
        });
      }
      this.productListFilter=this.productListFilter.filter(i=>i.productCode.toLowerCase().indexOf(this.productCode.toLowerCase())==0);
    },
    boxChange(bool){
      let self=this;
      if(bool){
        self.isShow.isShowPend=false;
      }
      self.productListFilter=JSON.parse(JSON.stringify(self.productList));
      if(self.selectedBox.length==0){
        if(!isEmpty(self.selectedPackage.id)){
          self.productListFilter.forEach(product=>{
            for(let i=0;i<product.productItemVoList.length;i++){
              let bool=false;
              self.packBoxArray.forEach(box=>{
                if(!isEmpty(product.productItemVoList[i].boxArray)&&product.productItemVoList[i].boxArray.filter(arr=>arr.boxId==box.id).length>0){
                  bool=true;
                }
              })
              if(!bool){
                product.productItemVoList.splice(i,1);
                i--;
              }
            }
          });
        }
      }else{
        self.productListFilter.forEach(product=>{
          for(let i=0;i<product.productItemVoList.length;i++){
            let bool=false;
            self.selectedBox.forEach(id=>{
              if(!isEmpty(product.productItemVoList[i].boxArray)&&product.productItemVoList[i].boxArray.filter(arr=>arr.boxId==id).length>0){
                bool=true;
              }
            })
            if(!bool){
              product.productItemVoList.splice(i,1);
              i--;
            }
          }
        });
      }
      this.productListFilter=this.productListFilter.filter(i=>i.productCode.toLowerCase().indexOf(this.productCode.toLowerCase())==0);
    },
    pendingProduct(value){
      this.selectedBox.splice(0,this.selectedBox.length);
      this.selectedPackage={};
      this.productListFilter=JSON.parse(JSON.stringify(this.productList));
      if(value){
        this.productListFilter.forEach(product=>{
          for(let i=0;i<product.productItemVoList.length;i++){
            if(product.productItemVoList[i].number==product.productItemVoList[i].sumBoxCount){
              product.productItemVoList.splice(i,1);
              i--;
            }
          }
        });
      }
      this.productListFilter=this.productListFilter.filter(i=>i.productCode.toLowerCase().indexOf(this.productCode.toLowerCase())==0);
    },
    handleChange1 (newTargetKeys) {
      this.targetData = newTargetKeys;
    },
    boxLabel(item){
      return item.name;
    },
    getSourceData () {
      let self=this;
      let data = [...self.packageBoxList.filter(box=>isEmpty(box.packageId)),...self.package.packageBoxList];
      data.forEach(item=>{
        item.key=item.id;
      })
      return data;
    },
    getTargetData () {
      let data = [];
      this.package.packageBoxList.forEach(item=>{
        data.push(item.id);
      })
      return data;
    },
    checkChange(val) {
      if (this.boxSelected.length == this.packageBoxList.filter(box=>isEmpty(box.packageId)).length) {
        this.isCheckedAllBox = true;
      } else {
        this.isCheckedAllBox = false;
      }
    },
    handleCheckAll() {
      let self = this;
      if (this.isCheckedAllBox) {
        this.boxSelected.splice(0, this.boxSelected.length);
        self.boxSelected=[...this.packageBoxList.filter(box=>isEmpty(box.packageId))];
      } else {
        this.boxSelected.splice(0, this.boxSelected.length);
      }
    },
    checkChangeColor(val) {
      if (tiyData.tParams.addProduct.colorItemIds.length == this.productInfo.productItemVoList.length) {
        this.isCheckedAllColor = true;
      } else {
        this.isCheckedAllColor = false;
      }
    },
    colorCheckAll() {//色卡 全选
      let self = this;
      if (this.isCheckedAllColor) {
        tiyData.tParams.addProduct.colorItemIds.splice(0, tiyData.tParams.addProduct.colorItemIds.length);
        self.productInfo.productItemVoList.forEach(item=>{
          if(isEmpty(item.packageBoxId)){
            tiyData.tParams.addProduct.colorItemIds.push(item.id);
          }
        })

      } else {
        tiyData.tParams.addProduct.colorItemIds.splice(0, tiyData.tParams.addProduct.colorItemIds.length);
      }

    },
    batchCheck(color,product){
      let tem=false;
      product.productItemVoList.forEach(function(item){
        if(isEmpty(item.packageBoxId)&&item.checked){
          tem=true;
        }
      })
      product.checkAll=tem;
    },
    batchCheckAll(product){
      product.productItemVoList.forEach(function(item){
        item.checked=product.checkAll;
      })
    },
    isEmpty(val) {
      return isEmpty(val);
    },
    resetRadioLabel(name){
      this.radioLabel=1;
      if(name==3){
        queryNotQualityProducts(this, tiyData, this.$route.params.shortOrderInfo.id);
      }
    },
    getLabel(pIndex,pck){
      return '运单号:'+pck.waybill;
    },
    showPackageModal(type,pack){
      if(type==1){
        this.boxSelected.splice(0, this.boxSelected.length);
        this.isCheckedAllBox = false;
        this.package.id = "";
        this.package.waybill = "";
        this.package.deliveryCompany = "";
        this.package.packageBoxList.splice(0,this.package.packageBoxList.length);
      }
      if(type==2){
        this.package=pack;
        this.sourceData=this.getSourceData();
        this.targetData=this.getTargetData();

      }

      tiyData.tStatus.modalPackage.type = type;
      tiyData.tStatus.modalPackage.isShow = true;
    },
    dropdownClick(name,box){
      if(name==1){
        this.showPackageBoxModal(2,box);
      }
      if(name==2){
        this.deleteBox(box);
      }
    },
    showPackageBoxModal(type,box){
      if(type==1){
        this.packageBox.id = "";
        this.packageBox.packageId = "";
        this.packageBox.name = "";
        this.packageBox.type = "1";
        this.packageBox.size = "";
        this.packageBox.weight = "";
      }
      if(type==2){
        this.packageBox.id = box.id;
        this.packageBox.packageId = box.packageId;
        this.packageBox.name = box.name;
        this.packageBox.type = box.type.toString();
        this.packageBox.size = box.size;
        this.packageBox.weight = box.weight;
      }
      tiyData.tStatus.modalPackageBox.type = type;
      tiyData.tStatus.modalPackageBox.isShow = true;
    },
    batchAddProduct(name){//包裹 添加产品
      tiyData.tParams.addProduct.colorItemIds.splice(0,tiyData.tParams.addProduct.colorItemIds.length);
      this.productListFiltered.forEach(product=>{
        product.productItemVoList.forEach(function(item){
          if(item.checked){
            let temp={
               "incomingProductId":item.id,
               "packageBoxId":tiyData.tParams.addProduct.boxId,
               "boxCount":item.boxCount,
            };
            tiyData.tParams.addProduct.colorItemIds.push(temp);
          }
        })
      })

      addProduct(this,tiyData,name);
    },
    addProduct(name){//产品加入到包裹
      addProduct(this,tiyData,name);
    },
    showAddProduct(product){
      this.productInfo=Object.assign({},product);

      this.isCheckedAllColor=false;
      tiyData.tParams.addProduct.boxId='';
      tiyData.tParams.addProduct.colorItemIds.splice(0,tiyData.tParams.addProduct.colorItemIds.length);
      tiyData.tStatus.modalProductAdd.isShow = true;
    },
    showBatchAddProduct(item){
      this.productListFiltered=JSON.parse(JSON.stringify(this.productListFilter.filter(i=>i.checkAll)));
      if(this.productListFiltered.length==0){
        this.$Message.error("请选择产品");
        return;
      }
      this.productListFiltered.forEach(product=>{
        for(let i=0;i<product.productItemVoList.length;i++){
          if(!product.productItemVoList[i].checked){
            product.productItemVoList.splice(i,1);
            i--;
          }else{
            if(product.productItemVoList[i].sumBoxCount>=product.productItemVoList[i].number){
              product.productItemVoList.splice(i,1);
              i--;
            }else {
              product.productItemVoList[i].boxCount=product.productItemVoList[i].number-product.productItemVoList[i].sumBoxCount;
            }
          }
        }
      })
      tiyData.tParams.addProduct.boxId="";
      tiyData.tParams.addProduct.colorItemIds.splice(0,tiyData.tParams.addProduct.colorItemIds.length);
      tiyData.tStatus.modalBatchProductAdd.isShow = true;
    },
    //新建物流单
    addPackage(name){
      if(tiyData.tStatus.modalPackage.type==1){
        this.package.packageBoxList=[...this.boxSelected];
      }
      if(tiyData.tStatus.modalPackage.type==2){
        let data=[];
        this.sourceData.forEach(item=>{
          if(this.targetData.indexOf(item.id)>=0){
            data.push(item);
          }
        })
        this.package.packageBoxList=[...data];
      }
      addPackage(this,tiyData,name);
    },
    addPackageBox(name){
      addPackageBox(this,tiyData,name);
    },
    back() {
      this.$router.go(-1);
    },
    getFormatedDateTime(time) {
      let formated = this.$tiyBJTime(time);
      return formated;
    },
    //取消款项未到账订单
    cancelUnconfirmedOrder() {
      this.$Modal.confirm({
        title: '取消订单',
        content: '<p>确认款项未到账，取消此订单？</p>',
        onOk: () => {
          cancelUnconfirmedOrder(this, tiyData);
        }
      });
    },
    //查看产品货源信息
    showProductSupply(productId) {
      showProductSupply(this, tiyData, productId);
    },
    getDictName(dict, value) {
      let cDict = this.$store.getters.dictionaries[dict];
      let name = "";
      if (cDict) {
        let dict = cDict.filter(function (item) {
          return item.value == value
        })
        if (dict.length > 0) {
          name = dict[0].name;
        }
      }
      return name;
    },
    //订单操作记录
    showItemRecord(orderItem) {
      tiyData.tStatus.modalRecord.title = "订单项记录";
      tiyData.tStatus.modalRecord.recordType = 3;
      tiyData.tStatus.modalRecord.info.productCode = orderItem.productCode;
      tiyData.tStatus.modalRecord.info.productColor = orderItem.color;
      tiyData.tStatus.modalRecord.info.productSize = orderItem.sizeName;

      webItemRecord(this, tiyData, orderItem.id);
    },
    showPackageRecord(orderPackage) {
      tiyData.tStatus.modalRecord.title = "包裹记录";
      tiyData.tStatus.modalRecord.recordType = 2;
      webPackageRecord(this, tiyData, this.orderId, orderPackage.id);
    },
    refundItems() {
      refundItems(this, tiyData);
    },
    orderDeliver(type, packageId) {
      if (type == 1 && (tiyData.tStatus.modalDeliver.params.selectedOrderItem.length <= 0
        || tiyData.tStatus.modalDeliver.params.selectedOrderItem[0].packageId != packageId)) {
        this.$Modal.error({
          title: "error",
          content: "请先选择需要发货的订单项！",
          width: 500,
          onOk: function () {
          }
        });
        return;
      }
      deliver(this, tiyData, type);
    },
    getBoxColor(boxId){
      let colors = ["#4caf50","#009688","#786548","#00bcd4",
        "#2196f3","#607d8b","#9c27b0",
        "#e91e63","#ff9800","#3f51b5",
      "#ef6c00","#757575","#37414f","#004d40"];
      let colorValue = "";
      this.packageBoxList.forEach(function (item,index) {
        if (boxId==item.id&&index<colors.length){
          colorValue = colors[index];
        }
      });

      return colorValue;

    },
  },
  mounted() {
    let order=this.$route.params.shortOrderInfo;
    this.package.orderId=order.id;
    this.package.serialNumber=order.serialNumber;
    this.package.method=order.deliveryMethod;
    this.packageBox.orderId=order.id;
    this.notQualityCheckProducts.splice(0,this.notQualityCheckProducts.length);
    getPackageInfo(this, tiyData, this.$route.params.shortOrderInfo.id,true);
  },
  computed:{

  }
}
</script>

<style scoped lang="less">
@import  (once,optional) "../css/base.less";

.order_product_div {
  margin-top: 1rem;

}


.order_product_row {
  padding: 1rem;
  border: .0625rem solid #dbdbdb;
  border-bottom-style: none;
}
.order_product_row_top {
  padding: 1rem;
  border: .0625rem #dbdbdb;
  border-top-style: solid;
}

.modal_new_form {
  padding-left: 30px;
  padding-top: 30px;
  padding-bottom: 30px;
}

.modal_form_input {
  width: 240px;
  margin-right: 10px;
}

.item_hover{
  padding: 0.5rem 0.5rem;
}
.item_hover:hover{
  background: #f3f3f3;
}
.ivu-tag-dot-inner{
  width: 10px !important;
  height: 10px !important;
}

</style>
